<?php

namespace App\Core\Database;

class RedisLock
{

    public function get($callback = null)
    {
        $result = $this->acquire();

        if ($result && is_callable($callback)) {
            try {
                return $callback();
            } finally {
                $this->release();
            }
        }

        return $result;
    }

    public function lock($name, $seconds, $callback = null)
    {
        $starting = time();
        $owner = 

        while (! static::acquire($name, $owner)) {
            usleep(250 * 1000);

            if ($this->currentTime() - $seconds >= $starting) {
                throw new LockTimeoutException;
            }
        }

        if (is_callable($callback)) {
            try {
                return $callback();
            } finally {
                $this->release();
            }
        }

        return true;
    }

    public static function acquire($name, $owner)
    {
        $result = Redis::setnx($this->name, $this->owner);

        if ($result === 1 && $this->seconds > 0) {
            Redis::expire($this->name, $this->seconds);
        }

        return $result === 1;
    }

    public function release($name, $owner)
    {
        Redis::eval(LuaScripts::releaseLock(), 1, $name, $owner);
    }
}